package cn.easyutil.project.web.handler;

import cn.easyutil.project.base.exception.CommonException;
import cn.easyutil.project.base.exception.Error;
import cn.easyutil.util.javaUtil.LoggerUtil;
import cn.easyutil.util.javaUtil.StringUtil;
import cn.easyutil.project.web.advice.RawRequestAdvice;
import cn.easyutil.project.web.util.RequestPool;

import javax.servlet.http.HttpServletRequest;

public class DefaultRawRequestAdvice implements RawRequestAdvice {
    @Override
    public String process(String bodyContext, HttpServletRequest request, Class<?> controllerClass) {
        String requestUri = request.getRequestURI();
        String callNoStr = request.getRequestURI().substring(requestUri.lastIndexOf("/") + 1);
        // 是否加解密
        if (!RequestPool.ENABLE_AUTH) {
            return bodyContext;
        }
        //加密的情况下，指定接口不加密
        if (!callNoStr.startsWith(RequestPool.ENABLE_AS_LAST_URI_PREFIX)) {
            return bodyContext;
        }
        //解密处理
        //获取用户的解密token
        String aesKey = RequestPool.getAESKey();

        LoggerUtil.info(this.getClass(),"[" + callNoStr + "]aesKey=" + aesKey + ",请求密文为:" + bodyContext);
        Long userId = RequestPool.getUserId();
        LoggerUtil.info(this.getClass(),"[" + callNoStr + "]请求用户id为:" + userId);
        //对数据进行解密
        try {
            bodyContext = StringUtil.AESDecode(bodyContext, aesKey);
        } catch (Exception e) {
            throw new CommonException(Error.request_not_token);
        }
        return bodyContext;
    }
}
